<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属模块" prop="bannerRegion" label-width="110">
        <el-select v-model="queryParams.bannerRegion" placeholder="请选择"   @change="handleQuery">
          <el-option
            v-for="dict in banner_region"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:bannerManager:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:bannerManager:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:bannerManager:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:bannerManager:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerManagerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="一级页面" align="center" prop="picUrl">
        <template #default="scope">
          <template v-if="previewListResource && checkFileSuffix(scope.row.fileSuffix)">
            <template
              v-for="item in scope.row.picUrl.split(',')"
              :key="item"
            >
              <image-preview :src="item" :width="50" :height="50"/>
            </template>
          </template>
          <video
            controls
            muted
            :width="200" :height="200"
            v-if="previewListResource && checkVedioFileSuffix(scope.row.fileSuffix)"
            type="video/mp4" :src="scope.row.picUrl">
          </video>
        </template>
      </el-table-column>
      <el-table-column label="二级页面类型" align="center" prop="linkType">
        <template #default="scope">
          <dict-tag :options="banner_link_type" :value="scope.row.linkType"/>
        </template>
      </el-table-column>
      <el-table-column label="二级页面" align="center" prop="link"/>
      <el-table-column label="所属模块" align="center" prop="bannerRegionName">
        <template #default="scope">
          <dict-tag :options="banner_region" :value="scope.row.bannerRegion"/>
        </template>
      </el-table-column>
      <el-table-column label="展示顺序" align="center" prop="sortOrder"></el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['business:bannerManager:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['business:bannerManager:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="bannerManagerRef" :model="form" :rules="rules" label-width="80px">
        <el-col :span="14">
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择" @change="uploadTypeChanged">
              <el-option
                v-for="dict in banner_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="所属模块" prop="type">
            <el-select v-model="form.bannerRegion" placeholder="请选择">
              <el-option
                v-for="dict in banner_region"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-form-item label="轮播图地址" prop="picUrl">
          <!--          <el-input v-model="form.picUrl" type="textarea" placeholder="请输入内容" />-->
          <image-uploads v-if="uploadFileType === '1' || uploadTypeChanged === 'undefined' " v-model="form.picUrl" limit="1"></image-uploads>
          <video-upload v-if="uploadFileType === '2'" v-model="form.picUrl" limit="1"></video-upload>
        </el-form-item>

        <el-col :span="14">
          <el-form-item label="跳转类型" prop="linkTpe">
            <el-select v-model="form.linkType" placeholder="请选择" @change="linkTpeChanged">
              <el-option
                v-for="dict in banner_link_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-form-item label="跳转地址" prop="link">
          <!--          <el-input v-model="form.picUrl" type="textarea" placeholder="请输入内容" />-->
          <el-input
            v-if="bannerLinkType === '1' || bannerLinkType === undefined "
            v-model="form.link"
            placeholder="请输入跳转外链"
          />

          <el-input
            v-if="bannerLinkType === '2' "
            v-model="form.link"
            placeholder="请输入跳转内链"
          />
          <image-uploads
            v-if="bannerLinkType === '3'"
            v-model="form.link"
            limit="1">

          </image-uploads>

          <el-input
            v-if="bannerLinkType === '4' "
            v-model="form.link"
            placeholder="请输入文本内容"
          />
        </el-form-item>

        <el-form-item label="顺序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="显示状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value + ''"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BannerManager">
import {
  listBannerManager,
  getBannerManager,
  delBannerManager,
  addBannerManager,
  updateBannerManager
} from "@/api/business/bannerManager";
import VideoUpload from "@/components/VideoUpload/index.vue";
import ImageUploads from "@/components/ImageUploads/index.vue";
import {ref} from "vue"
import {getLightColor} from "../../../utils/theme";


const {proxy} = getCurrentInstance();

const {sys_show_hide, sys_normal_disable, banner_link_type, banner_type, banner_region}
  = proxy.useDict("sys_show_hide", "sys_normal_disable", "banner_link_type", "banner_type", "banner_region");
const bannerManagerList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//跳转类型判断
const bannerLinkType = ref(1);
//上传文件类型判断
const uploadFileType = ref('1');
const previewListResource = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    picUrl: undefined,
    sortOrder: undefined,
    status: undefined,
  },
  rules: {
    id: [
      {required: true, message: "id不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "类型不能为空", trigger: "change"}
    ],
    picUrl: [
      {required: true, message: "轮播图地址不能为空", trigger: "blur"}
    ],
    sortOrder: [
      {required: true, message: "顺序不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "状态(0:正常 1:停用)不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/* 判断图片类型 */
function checkFileSuffix(fileSuffix) {
  let arr = ["png", "jpg", "jpeg"];
  return arr.some(type => {
    return fileSuffix.indexOf(type) > -1;
  });
}

/* 判断文件类型 */
function checkVedioFileSuffix(fileSuffix) {

  let arr = ["mp4", "avi", "rmvb", "rm"];
  return arr.some(type => {
    return fileSuffix.indexOf(type) > -1;
  });
}

/* 动态展示文件上传类型 */
function uploadTypeChanged(e){
  console.log(e)
  uploadFileType.value = e
}

/* 动态显隐跳转链接类型 */
function linkTpeChanged(e){
  bannerLinkType.value = e
}

/* 查询轮播图管理列表 */
function getList() {
  console.log(proxy)
  loading.value = true;
  listBannerManager(queryParams.value).then(response => {
    bannerManagerList.value = response.rows;
    total.value = response.total;
    console.log(response.rows)
    for (let i = 0; i < response.rows.length; i++) {
      console.log(response.rows[i])
      let bannerManagerListKey = response.rows[i]
      if(bannerManagerListKey.picUrl && typeof bannerManagerListKey.picUrl === 'string'){
        // 获取 URL 的文件名部分
        const filename = bannerManagerListKey.picUrl.substring(bannerManagerListKey.picUrl.lastIndexOf('/') + 1);
        console.log(bannerManagerListKey.picUrl)
        console.log(filename)
        // 使用正则表达式匹配文件后缀名
        const extension = filename.match(/\.[^.]*$/);
        if (extension) {
          // 提取文件后缀名（不包括点）
          const fileExtension = extension[0];
          // 打印文件后缀名
          response.rows[i].fileSuffix = fileExtension;
        } else {
          // URL 没有文件后缀名
          console.log('URL 没有文件后缀名');
        }
      }
    }
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    picUrl: null,
    sortOrder: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("bannerManagerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加轮播图管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getBannerManager(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    form.value.type = response.data.type.toString()
    form.value.status = response.data.status.toString()
    bannerLinkType.value = response.data.linkType
    open.value = true;
    title.value = "修改轮播图管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bannerManagerRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateBannerManager(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addBannerManager(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除轮播图管理编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delBannerManager(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/bannerManager/export', {
    ...queryParams.value
  }, `bannerManager_${new Date().getTime()}.xlsx`)
}

getList();
</script>
